import html2canvas from "html2canvas";
var innerHeight = document.body.clientHeight;
export default {
  data() {
    return {
      innerHeight: innerHeight,
      star_time: null,
      time: "",
      Day: "01", //剩余天
      Hour: "03", //剩余小时
      Min: "32", //剩余分钟
      Sec: "34", //剩余秒
      stop: false, //判断活动是否结束
      show: false,
      loadingImg: true,
      dataURL: "",
      info: {
        avatar: null,
        nickname: null,
        qr_code: null,
        cover: null
      },
      isSetNotice: false,
      end: null,
      PosterData: {},
      posterImg: [],
      base64Datas: []
    };
  },
  activated() {
    let {CAT,STAT,REC,RId} = this.$route.query;
    this.RId = RId;
    this.CAT = CAT||'';
    this.STAT = STAT||'';
    this.REC = REC||'';

    this.initData();
    this.getData();
  },
  deactivated(){
    if(this.pollStautsTimer) clearInterval(this.pollStautsTimer);
  },
  methods: {
    initData() {
      this.time = "";
      this.Day = ""; //剩余天
      this.Hour = ""; //剩余小时
      this.Min = ""; //剩余分钟
      this.Sec = ""; //剩余秒
      this.show = false;
      this.isSetNotice = false;
      this.info = {
        avatar: null,
        nickname: null,
        qr_code: null,
        cover: null
      };
      this.star_time = null;
      this.end = null;
      this.PosterData = {};
      this.posterImg = [];
      this.base64Datas = [];
      this.loadingImg = true;
    },
    getData() {
      $http
        .post("plugin.share-room.frontend.controllers.index.room-notice", { room_id: this.RId }, "")
        .then(response => {
          if (response.result === 1) {
            this.info = response.data;
            if (response.data.status == 1) {
              this.$toast("已开播，正在为您跳至直播间！");
              return this.$router.push(this.fun.getUrl("shareRoomPlayer", {},{RId: this.RId, CAT: this.CAT, STAT: 1, REC: this.REC}));
            }
            if (response.data.status == 2) {
              this.$toast("直播已结束，正在为您跳至主播页面！");
              return this.$router.push(this.fun.getUrl("shareRoomPlayer", {},{RId: this.RId, CAT: this.CAT, STAT: 2, REC: this.REC}));
            }
            this.fun.wxShare(
              "",
              {},
              {
                title: this.info.member.nickname,
                imgUrl: this.info.cover,
                description: "邀请您进入直播间"
              }
            );
          } else {
            this.$toast(response.msg);
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    getPoster() {
      if (!this.loadingImg && this.dataURL) {
        return this.show = true;
      }
      this.powerToast = this.$toast({
        duration: -1, // 持续展示 toast
        message: "正在为您生成海报中，请稍后"
      });
      $http
        .post("plugin.share-room.frontend.controllers.index.room-post", { room_id: this.RId}, "")
        .then(response => {
          if (response.result === 1) {
            this.posterImg.push(this.$store.state.temp.mailInfo?.logo, this.info.member.avatar, response.data.qr_code);
            this.loop();
          } else {
            this.$toast(response.msg);
          }
        })
        .catch(error => {
          console.log(error);
        });
    },
    async loop() {
      for (let i = 0; i < this.posterImg.length; i++) {
        await this.onloadImg(this.posterImg[i], i);
      }
      this.$nextTick(() => {
        setTimeout(() => {
          this.saveImg();
        }, 1000);
        setTimeout(() => {
          this.loadingImg = false;
        }, 3000);
      });
    },
    onloadImg(data, i, type) {
      return new Promise((resolve, reject) => {
        //一定要设置为let，不然图片不显示
        let image = new Image();
        //解决跨域问题
        image.setAttribute("crossOrigin", "anonymous");

        let imageUrl = data;
        // let scale = window.devicePixelRatio; //定义任意放大倍数 支持小数
        image.src = `${imageUrl}?${Date.now()}`;
        let that = this;
        //image.onload为异步加载
        image.onload = () => {
          var canvas = document.createElement("canvas");
          canvas.width = image.width;
          canvas.height = image.height;
          var context = canvas.getContext("2d");
          context.drawImage(image, 0, 0, image.width, image.height);

          var quality = 0.8;
          //这里的dataurl就是base64类型
          var dataURL = canvas.toDataURL("image/png", quality); //使用toDataUrl将图片转换成jpeg的格式,不要把图片压缩成png，因为压缩成png后base64的字符串可能比不转换前的长！
          that.base64Datas.push(dataURL);
          console.log("转换图片成功 =====success=====", i);

          resolve();
        };
        image.onerror = () => {
          that.base64Datas.push("");
          console.log("转换图片报错  ===== error ===", i);
          resolve();
          // that.getError()
        };
      });
    },
    showPoster() {
      if (this.dataURL) {
        this.show = true;
      }
      if(this.powerToast) {
        //取消海报生成提示，防止退出直播间后还在提示
        this.powerToast.clear();
      }
    },
    shareMessage() {
      this.$dialog.alert({ message: "请生成海报或点击右上角分享" });
    },
    saveImg() {
      this.dataURL = null;
      var content = document.getElementById("code_box");
      const that = this;
      html2canvas(content, {
        useCORS: true,
        backgroundColor: null // 解决生成的图片有白边
      }).then(canvas => {
        that.dataURL = canvas.toDataURL("image/png"); //创建base64图片
        document.getElementById("thecanvas").setAttribute("src", that.dataURL);
        that.showPoster();
      });
    },
    goto() {
      this.$router.push(this.fun.getUrl("shareRoomList"));
    },
    finishtime(){
      this.pollStautsTimer = setInterval(() => {
        this.pollingLiveStatus();//轮询直播状态，开播直接跳转
      }, 15000);
    },
    async pollingLiveStatus() {
      let { result, data } = await $http.get("plugin.share-room.frontend.controllers.index.room-notice", { room_id: this.RId }, "加载中");
      if (result == 1 && data.status == 1) {
        if(this.pollStautsTimer) clearInterval(this.pollStautsTimer);
        this.$toast("已开播，正在为您跳至直播间！");
        return this.$router.push(this.fun.getUrl("shareRoomPlayer", {},{RId: this.RId, CAT: this.CAT, STAT: 1, REC: this.REC}));
      }
    },
  },
  computed: {
    nameEllipsis() {
      if (this.info.member && this.info.member.nickname) {
        return this.info.member.nickname.length > 4 ? this.info.member.nickname.substring(0, 4) + "..." : this.info.member.nickname;
      }
    }
  },
  components: {}
};
